//
//  CommodityHeaderView.swift
//  StarTimesTV
//
//  Created by 胡月明 on 2019/1/2.
//  Copyright © 2019年 StarTimes. All rights reserved.
//

import UIKit

class DoubleLabel: UIView {
    
    lazy var nameLabel:UILabel = {
        let label = UILabel.init()
        label.numberOfLines = 1
        label.font = UIFont.regular(with: fontSize14)
        label.textColor = STColor.olGold
        return label
    }()
    
    lazy var contentLabel:UILabel = {
        let label = UILabel.init()
        label.numberOfLines = 0
        label.font = UIFont.regular(with: fontSize14)
        label.textColor = STColor.olGold
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(nameLabel)
        addSubview(contentLabel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reload(name:String?,content:String?) -> CGFloat{
        let viewWidth = KScreenW-scale_width(76)
        
        nameLabel.text = name
        contentLabel.text = content
        
        let width = name?.getLableWidth(font: UIFont.regular(with: fontSize14), height: margin20) ?? 0
        var height = (content?.getLableHeight(font: UIFont.regular(with: fontSize14), width: viewWidth-width)) ?? 0
        if (height <= margin20 && (height>0)){
            height = scale_width(15)
        }
        nameLabel.frame = CGRect(x: 0, y: 0, width: width, height: scale_width(15))
        contentLabel.frame = CGRect(x: width, y: 0, width: viewWidth-width-margin10, height: height)
        
        return height
    }
    
    func setTextColor(color:UIColor) {
        nameLabel.textColor = color
        contentLabel.textColor = color
    }
    
}


class CommodityHeaderView: UIView {
    
    var productModel:MemberProductDto?
    
    private lazy var iconImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(resourceName: "avatar"))
        imageView.layer.cornerRadius = scale_width(24)
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    private lazy var iconCrownView: UIImageView = {
        let imageView = UIImageView(image:UIImage(resourceName:"ic_crown_def_golden"))
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.isHidden = true
        return imageView
    }()
    
    private lazy var vipImageView: UIImageView = {
        let imageView = UIImageView(image:UIImage(resourceName:"ic_vip_def_golden"))
        imageView.clipsToBounds = true
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.cornerRadius = scale_width(3)
        imageView.isHidden = true
        return imageView
    }()
    
    private lazy var suspandImageView: UIImageView = {
        let imageView = UIImageView(image:UIImage(resourceName:"vipsuspand"))
        imageView.contentMode = .scaleAspectFill
        imageView.isHidden = true
        return imageView
    }()
    
    private lazy var contentView: UIView = {
        let view = UIView.init()
        return view
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel.init()
        label.numberOfLines = 1
        label.font = UIFont.bold(with: fontSize16)
        label.textColor = STColor.olGold
        label.textAlignment = .left
        label.isHidden = true
        
        return label
    }()
    
    private lazy var centerLabel: DoubleLabel = {
        let label = DoubleLabel.init()
        label.isHidden = true
        return label
    }()
    
    private lazy var bottomLabel: DoubleLabel = {
        let label = DoubleLabel.init()
        label.isHidden = true
        return label
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame:.zero)
        setUpUI()
    }
    
    //登录成功之后
    @objc func updateHeaderViewLoginStatus(){
        STUserModel.shared.isLogin() ? setData(): setNoLogData()
    }

    
    func setNoLogData(){
        self.signButton.isHidden = false
        self.nameLabel.isHidden = true
        self.centerLabel.isHidden = true
        self.bottomLabel.isHidden = true
        self.vipImageView.isHidden = true
        self.iconCrownView.isHidden = true
        iconImageView.st_setImage(with: STUserModel.shared.meInfoDto?.avatar, placeholder: UIImage(resourceName: "avatar"))
        self.suspandImageView.isHidden = true
        self.contentView.isHidden = true
    }
    
    func setLoginData(){
        self.signButton.isHidden = true
        self.nameLabel.isHidden = false
        self.centerLabel.isHidden = false
        self.bottomLabel.isHidden = false
        self.vipImageView.isHidden = false
        self.iconCrownView.isHidden = false
        self.suspandImageView.isHidden = false
        self.contentView.isHidden = false
        iconImageView.st_setImage(with: STUserModel.shared.meInfoDto?.avatar, placeholder: UIImage(resourceName: "avatar"))
        self.nameLabel.text = STUserModel.shared.meInfoDto?.nickname
    }
    
    func setData(){
        
        setLoginData()
        
        if(self.productModel != nil){
            
            var isVip = false
            
            var tempItem:OttOrderInstant?
            
            let subscribedPacketList = OTTService.shared.subscribedPackageList
            
            var centerH:CGFloat = 0
            var bottomH:CGFloat = 0
            
            for item in subscribedPacketList{
                if productModel?.id == Int(item.product_id){

                    let remainTimeTitle: String = OLLocalize("remaining_time", comment: "")
                    let expiredTimeTitle: String = OLLocalize("expired_time", comment: "")
                    
                    if item.remaining_ratings_time > 0 {
                        centerH = centerLabel.reload(name: remainTimeTitle, content: convertFormatHourMinFrom(seconds: Int64(item.remaining_ratings_time)))
                    }else{
                        centerH = centerLabel.reload(name: nil, content: nil)
                    }
                    
                    if let endTime = DateFormat.date(fromServer: item.end_time){
                        bottomH = bottomLabel.reload(name: expiredTimeTitle, content: DateFormat.mmmdyhmFormatter.string(from: endTime))
                    }else{
                        bottomH = bottomLabel.reload(name: nil, content: nil)
                    }
                    
                    tempItem = item
                    isVip = true
//                    break
                }
            }
            
            
            if isVip{
                self.nameLabel.textColor = STColor.olGold
                self.centerLabel.setTextColor(color: STColor.olGold)
                self.bottomLabel.setTextColor(color: STColor.olGold)
                
                if tempItem?.status == .valid{
                    self.vipImageView.image = UIImage.init(named: "ic_vip_def_golden")
                    self.iconCrownView.image = UIImage.init(named:"ic_crown_def_golden")
                    self.suspandImageView.isHidden = true
                }else{
                    self.vipImageView.image = UIImage.init(named:"ic_vip_def_g")
                    self.iconCrownView.image = UIImage.init(named:"ic_crown_def_g")
                }
                
                if(productModel?.product_type == .dataFree){
                    
                    let nameH = margin16
                    let top = (self.frame.size.height - nameH - centerH - bottomH - margin4*2)/2.0
                    self.nameLabel.frame = CGRect(x: 0, y: top, width: self.frame.size.width, height: nameH)
                    
                    self.centerLabel.frame = CGRect(x: 0, y: top+nameH+margin4, width: self.frame.size.width, height: bottomH)
                    
                    self.bottomLabel.frame = CGRect(x: 0, y: top+nameH+centerH+margin4*2, width: self.frame.size.width, height: bottomH)
                }else{
                    self.centerLabel.isHidden = true
                    let nameH = margin16
                    let top = (self.frame.size.height - nameH - margin4 - bottomH)/2.0
                    self.nameLabel.frame = CGRect(x: 0, y: top, width: self.frame.size.width, height: nameH)
                    self.bottomLabel.frame = CGRect(x: 0, y: top+nameH+margin4, width: self.frame.size.width, height: bottomH)
                }

            }else{
                
                self.nameLabel.textColor = UIColor.white
                self.centerLabel.setTextColor(color: UIColor.white)
                self.bottomLabel.setTextColor(color: UIColor.white)
                
                self.vipImageView.isHidden = true
                self.iconCrownView.isHidden = true
                self.suspandImageView.isHidden = true
                self.centerLabel.isHidden = true

                bottomH = self.bottomLabel.reload(name: nil, content: OLLocalize("membership_not_subscribe"))
                let nameH = margin16
                let top = (self.frame.size.height - nameH - margin4 - bottomH)/2.0
                self.nameLabel.frame = CGRect(x: 0, y: top, width: self.frame.size.width, height: nameH)
                self.bottomLabel.frame = CGRect(x: 0, y: top+nameH+margin4, width: self.frame.size.width, height: bottomH)
            }
            
  
        }else{//all
            
            var OttServiceArray:[String] = [String]()
            
            for item in OTTService.shared.subscribedPackageList{
                if item.status == .valid{
                    OttServiceArray.append(item.commodityDto?.product?.abbrev_name ?? "")
                }
            }
            
            let content = OLLocalize("membership_active_vip") + OttServiceArray.joined(separator:",")

            self.centerLabel.isHidden = true
            self.suspandImageView.isHidden = true
            
            var height:CGFloat = 0
            
            if (OttServiceArray.count > 0){// vip
                self.vipImageView.image = UIImage.init(named: "ic_vip_def_golden")
                self.iconCrownView.image = UIImage.init(named:"ic_crown_def_golden")
                height = self.bottomLabel.reload(name: nil, content: content)
                self.nameLabel.textColor = STColor.olGold
                self.bottomLabel.setTextColor(color: STColor.olGold)
            }else{
                self.vipImageView.isHidden = true
                self.iconCrownView.isHidden = true
                height = self.bottomLabel.reload(name: nil, content: OLLocalize("membership_not_subscribe"))
                self.nameLabel.textColor = UIColor.white
                self.bottomLabel.setTextColor(color: UIColor.white)
            }
            
            let nameH = margin16
            let top = (self.frame.size.height - nameH - margin4 - height)/2.0
            self.nameLabel.frame = CGRect(x: 0, y: top, width: self.frame.size.width, height: nameH)
            self.bottomLabel.frame = CGRect(x: 0, y: top+nameH+margin4, width: self.frame.size.width, height: height)
  
        }
        
        var OttServiceArray:[String] = [String]()
        
        for item in OTTService.shared.subscribedPackageList{
            if item.status == .valid{
                OttServiceArray.append(item.service_name)
            }
        }
        if (OttServiceArray.count > 0){// vip
            self.vipImageView.image = UIImage.init(named: "ic_vip_def_golden")
            self.iconCrownView.image = UIImage.init(named:"ic_crown_def_golden")
            self.vipImageView.isHidden = false
            self.iconCrownView.isHidden = false
        }else{
            self.vipImageView.isHidden = true
            self.iconCrownView.isHidden = true
        }
    }
    
    func convertFormatHourMinFrom(seconds: Int64) -> String {
       var formatTime: String = ""
       if seconds > OneMinInSeconds {
           let hour = seconds / OneHourInSeconds
           let minute = (seconds % OneHourInSeconds) / OneMinInSeconds
           var hourStr = ""
           var minuteStr = ""
           if hour > 1 {
               hourStr = "\(hour) hours"
           } else if hour == 1 {
               hourStr = "1 hour"
           }
           if minute > 1 {
               minuteStr = "\(minute) mins"
           } else if minute == 1 {
               minuteStr = "1 min"
           }
           formatTime = (hourStr + " " + minuteStr).trimmingWhiteSpaces()
       } else {
           if seconds > 1 {
               formatTime = "\(seconds) s"
           } else if seconds == 1 {
               formatTime = "1 s"
           } else {
               formatTime = ""
           }
       }
       return formatTime
    }
    
    private func attrsText(from text: String, tailText: String) -> NSAttributedString {
        let attrs: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: STColor.olGold, NSAttributedString.Key.font: UIFont.regular(with: 14)]
        let attrText = NSMutableAttributedString(string: text, attributes: attrs)
        
        let attrsTail: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: STColor.olGold, NSAttributedString.Key.font: UIFont.regular(with: 14)]
        let attrTailText = NSMutableAttributedString(string: tailText, attributes: attrsTail)
        attrText.append(attrTailText)
        return attrText
    }
    
    public func reload(productModel:MemberProductDto?){
        self.productModel = productModel
        updateHeaderViewLoginStatus()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI(){
        self.backgroundColor = .navigation
        self.addSubview(iconImageView)
        self.addSubview(iconCrownView)
        self.addSubview(vipImageView)
        self.addSubview(contentView)
        
        contentView.addSubview(centerLabel)
        contentView.addSubview(bottomLabel)
        contentView.addSubview(nameLabel)
        
        self.addSubview(signButton)
        self.addSubview(suspandImageView)
        
        self.iconImageView.snp.makeConstraints { (make) in
            make.height.width.equalTo(scale_width(48))
            make.left.equalTo(self.snp.left).offset(margin12)
            make.top.equalTo(self.snp.top).offset(margin8)
        }
        
        self.suspandImageView.snp.makeConstraints { (make) in
            make.top.right.bottom.equalToSuperview()
            make.width.equalTo(scale_width(82))
        }
        
        self.iconCrownView.snp.makeConstraints { (make) in
            make.right.equalTo(self.iconImageView.snp.right).offset(margin4)
            make.top.equalTo(self.iconImageView.snp.top).offset(-margin4)
            make.width.height.equalTo(margin20)
        }
        
        self.vipImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.iconImageView.snp.centerX)
            make.centerY.equalTo(self.iconImageView.snp.bottom)
            make.width.equalTo(scale_width(30))
            make.height.equalTo(margin12)
        }
        
        self.signButton.snp.makeConstraints { (make ) in
            make.leading.equalTo(iconImageView.snp.trailing).offset(margin20)
            make.centerY.equalTo(iconImageView)
            make.height.equalTo(scale_width(30))
            make.width.greaterThanOrEqualTo(0)
        }
 
        
        self.contentView.snp.makeConstraints { (make) in
            make.top.bottom.right.equalToSuperview()
            make.left.equalTo(iconImageView.snp.right).offset(margin16)
        }

    }
}
